package service

import (
	"strconv"
	"xianzhi/models"
	"github.com/astaxie/beego/orm"
	"net/url"
	"xianzhi/utils"
)

// 获取套餐信息
func GetSetMealInfo(p map[string]interface{}) *models.SetMeal {
	o := orm.NewOrm()
	setMeal := &models.SetMeal{}
	qs := o.QueryTable("SetMeal")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["name"]; ok {
		qs = qs.Filter("name", p["name"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	qs.One(setMeal)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if setMeal.Id > 0 {
			setMeal.StatusShow = models.SetMealStatus[setMeal.Status]
		}
	}
	return setMeal
}

// 添加套餐
func AddSetMeal(input url.Values) (int64, error) {
	o := orm.NewOrm()
	setMeal := &models.SetMeal{}
	if _, ok := input["name"]; ok {
		setMeal.Name = input["name"][0]
	}
	if _, ok := input["introduce"]; ok {
		setMeal.Introduce = input["introduce"][0]
	}
	if _, ok := input["price"]; ok {
		setMeal.Price = utils.Atof64(input["price"][0])
	}
	if _, ok := input["push_num"]; ok {
		setMeal.PushNum, _ = strconv.Atoi(input["push_num"][0])
	}
	if _, ok := input["excellent_num"]; ok {
		setMeal.ExcellentNum, _ = strconv.Atoi(input["excellent_num"][0])
	}
	if _, ok := input["assist_num"]; ok {
		setMeal.AssistNum, _ = strconv.Atoi(input["assist_num"][0])
	}
	if _, ok := input["status"]; ok {
		setMeal.Status, _ = strconv.Atoi(input["status"][0])
	}
	if _, ok := input["sort"]; ok {
		setMeal.Sort, _ = strconv.Atoi(input["sort"][0])
	}
	return o.Insert(setMeal)
}

// 修改套餐信息
func EditSetMeal(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("SetMeal").Filter("id", input["id"][0]).Update(p)
}

// 获取套餐列表
func GetSetMealList(p map[string]interface{}) (int64, []*models.SetMeal) {
	var setMealList []*models.SetMeal
	o := orm.NewOrm()
	qs := o.QueryTable("SetMeal")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["name"]; ok {
		qs = qs.Filter("name__contains", p["name"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("sort").All(&setMealList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, setMeal := range setMealList {
			setMeal.StatusShow = models.SetMealStatus[setMeal.Status]
		}
	}
	return totalCount, setMealList
}
